package com.qf.config;

import com.alibaba.fastjson2.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;

/**
 * --- 天道酬勤 ---
 *
 * @author QiuShiju
 * @desc
 */
@Component
public class AuthenticationEntryPointImpl  implements AuthenticationEntryPoint, Serializable {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        // 应该是R类,此项目没有设置,暂时使用Map代替
        HashMap<String, Object> result = new HashMap<>( );
        result.put("code", 40003);
        String msg = "请求访问："+request.getRequestURI()+"，认证失败，无法访问系统资源";
        result.put("msg", msg);
        // 将Map转换为JSON字符串(使用的是阿里fastjson2依赖)
        String r = JSON.toJSONString(result);
        // 响应出去
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.getWriter().println(r);
    }
}
